import logging
from sparkai.llm.llm import ChatSparkLLM
from sparkai.core.messages import ChatMessage
from django.conf import settings

logger = logging.getLogger(__name__)

class SparkAIHandler:
    def __init__(self, streaming=False):
        try:
            logger.info(f"初始化 SparkAI 处理器，配置信息：{settings.SPARKAI_CONFIG}")
            self.llm = ChatSparkLLM(
                spark_api_url=settings.SPARKAI_CONFIG['URL'],
                spark_app_id=settings.SPARKAI_CONFIG['APP_ID'],
                spark_api_key=settings.SPARKAI_CONFIG['API_KEY'],
                spark_api_secret=settings.SPARKAI_CONFIG['API_SECRET'],
                spark_llm_domain=settings.SPARKAI_CONFIG['DOMAIN'],
                streaming=streaming,
                temperature=0.7,  # 添加温度参数
                max_tokens=2048,  # 添加最大token参数
            )
            logger.info("SparkAI 处理器初始化成功")
        except Exception as e:
            logger.error(f"SparkAI 处理器初始化失败: {str(e)}", exc_info=True)
            raise

    def generate_response(self, messages):
        try:
            logger.info("开始生成响应")
            chat_messages = [
                ChatMessage(role=msg['role'], content=msg['content'])
                for msg in messages
            ]
            logger.info(f"处理消息: {chat_messages}")
            response = self.llm.generate([chat_messages])
            result = response.generations[0][0].text
            logger.info(f"生成响应成功: {result}")
            return result
        except Exception as e:
            logger.error(f"生成响应失败: {str(e)}", exc_info=True)
            raise

    async def generate_stream_response(self, messages):
        try:
            logger.info("开始流式生成响应")
            chat_messages = [
                ChatMessage(role=msg['role'], content=msg['content'])
                for msg in messages
            ]
            async for chunk in self.llm.agenerate([chat_messages]):
                yield chunk.generations[0][0].text
        except Exception as e:
            logger.error(f"流式生成响应失败: {str(e)}", exc_info=True)
            raise